package org.ee.framework.jpa.db;

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * 启动创建数据库逻辑
 * @Author jokr
 * @Date 2025/8/15 下午5:53
 */
//@Component
public class DatabaseInit implements ApplicationListener {

    private final JdbcTemplate jdbcTemplate;

    public DatabaseInit(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        String dbName="db_test_dev";
        // 检查数据库是否存在
        String checkDbSql = "SELECT COUNT(*) FROM information_schema.schemata WHERE schema_name = ?";
        Integer count = jdbcTemplate.queryForObject(checkDbSql, new Object[]{dbName}, Integer.class);

        // 如果数据库不存在，则创建
        if (count != null && count == 0) {
            String createDbSql = "CREATE DATABASE " + dbName;
            jdbcTemplate.execute(createDbSql);
            System.out.println("数据库 " + dbName + " 创建成功!");
        } else {
            System.out.println("数据库 " + dbName + " 已存在.");
        }
    }


}
